package com.yegs.jindie.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yegs.jindie.entity.*;
import com.yegs.jindie.util.HttpPloxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class InventoryService {

    @Autowired
    private AuthService authService;

    @Autowired
    private BasisTO basisTO;

    @Autowired
    private ToFactory toFactory;

    @Autowired
    private ProductService productService;

    private static final String deliveryURL = "https://api.kingdee.com/jdyscm/delivery/list?";
    private static final String purchaseURL = "https://api.kingdee.com/jdyscm/purchase/list?";
    private static final SimpleDateFormat sdf_filter = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat sdf_name = new SimpleDateFormat("yyyyMMdd");

    private String getPurchaseURL() throws Exception {
        String request_url = purchaseURL + "access_token="+ authService.getAccessToken() +"&dbId="+basisTO.getAppId();
        return request_url;
    }

    private String getDeliveryURL() throws Exception{
        String request_url = deliveryURL +  "access_token="+ authService.getAccessToken() +"&dbId="+basisTO.getAppId();
        return request_url;
    }

    private String getParams(Date beginDate, Date endDate, int page) throws Exception {
        String str_begin = sdf_filter.format(beginDate);
        String str_end = sdf_filter.format(endDate);
        JSONObject jo = new JSONObject();
        jo.put("beginDate",str_begin);
        jo.put("endDate",str_end);
        jo.put("pageSize",500);
        jo.put("page",page);
        JSONObject filter = new JSONObject();
        filter.put("filter",jo);
        return filter.toJSONString();
    }

    public List<InventoryTO> getInventory(Date beginDate, Date endDate)  throws Exception{
        List<PurchaseTO> putchases = this.getPutchase(beginDate, endDate);
        List<DeliveryTO> deliverys = this.getDelivery(beginDate, endDate);
        List<InventoryTO> inventoryTOS = new ArrayList<>();
        for(PurchaseTO pur : putchases){
            boolean b = true;
            for(DeliveryTO del : deliverys){
                if(pur.getImei().equals(del.getImei())){
                    b = false;
                    break;
                }
            }
            if(b){
                InventoryTO inventoryTO = toFactory.getInventoryTO(new Date(),pur.getImei(),pur.getPrice(),pur.getProductNumber());
                inventoryTOS.add(inventoryTO);
            }
        }
        return inventoryTOS;
    }

    private JSONArray repeatPost(JSONArray ja,String url, Date beginDate, Date endDate, int page)  throws Exception{
        String post = HttpPloxy.post(url, this.getParams(beginDate, endDate, page));
        JSONObject jsonObject = JSONObject.parseObject(post);
        JSONArray items = jsonObject.getJSONArray("items");
        if(items == null){
            System.out.println("无查询结果");
            return ja;
        }else if(jsonObject.getInteger("totalPages") == page){
            ja.addAll(items);
            return ja;
        }else{
            ja.addAll(items);
            return repeatPost(ja, url, beginDate, endDate,++ page);
        }
    }

    private JSONArray postPurchase(Date beginDate, Date endDate) throws Exception {
        JSONArray ja = new JSONArray();
        int page = 1;
        return repeatPost(ja,this.getPurchaseURL(),beginDate,endDate,page);
    }
    private JSONArray postDelivery(Date beginDate, Date endDate) throws Exception {
        JSONArray ja = new JSONArray();
        int page = 1;
        return repeatPost(ja,this.getDeliveryURL(),beginDate,endDate,page);
    }


    private List<PurchaseTO> getPutchase(Date beginDate, Date endDate) throws Exception{
        List<String> products = productService.getProduct();
        List<PurchaseTO> list = new ArrayList<PurchaseTO>();
        JSONArray items = this.postPurchase(beginDate, endDate);
        if(items == null){
            System.out.println("无查询结果");
            return list;
        }
        PurchaseTO purchaseTO = null;
        System.out.println(items);
        for(int i = 0; i < items.size(); i ++){
            JSONObject jo = items.getJSONObject(i);
            JSONArray entries = jo.getJSONArray("entries");
            for(int j = 0; j < entries.size(); j ++){
                JSONObject entity = entries.getJSONObject(j);
                String id = entity.getString("productId");
                if(this.checkBeing(id,products) && this.checkLocation(entity.getString("location"))){
                    if(entity.containsKey("serNumList")){
                        JSONArray serNumList = entity.getJSONArray("serNumList");
                        for(int k = 0; k < serNumList.size(); k ++){
                            String serNum = serNumList.getJSONObject(k).getString("serNum");
                            Date date = jo.getDate("date");
                            purchaseTO = toFactory.getPurchaseTO(date, serNum, entity.getString("price"),"Y",entity.getString("productName"));
                            list.add(purchaseTO);
                        }
                    }
                }
            }
        }
        return list;
    }

    private List<DeliveryTO> getDelivery(Date beginDate, Date endDate) throws Exception{
        List<String> products = productService.getProduct();
        List<DeliveryTO> list = new ArrayList<DeliveryTO>();
        JSONArray items = this.postDelivery(beginDate, endDate);
        if(items == null){
            System.out.println("无查询结果");
            return list;
        }
        DeliveryTO deliveryTO = null;
        for(int i = 0; i < items.size(); i ++){
            JSONObject jo = items.getJSONObject(i);
            JSONArray entries = jo.getJSONArray("entries");
            for(int j = 0; j < entries.size(); j ++){
                JSONObject entity = entries.getJSONObject(j);
                String id = entity.getString("productId");
                if(this.checkBeing(id,products) && this.checkLocation(entity.getString("location"))){
                    if(entity.containsKey("serNumList")){
                        JSONArray serNumList = entity.getJSONArray("serNumList");
                        for(int k = 0; k < serNumList.size(); k ++){
                            String serNum = serNumList.getJSONObject(k).getString("serNum");
                            Date date = jo.getDate("date");
                            deliveryTO = toFactory.getDeliveryTO(date, serNum, entity.getString("price"),null,entity.getString("productName"));
                            list.add(deliveryTO);
                        }
                    }
                }
            }
        }
        return list;
    }


    public String getFileName(Date endDate, Integer int_last) throws ParseException {
        String delivery_pre = basisTO.getInventory_pre();
        return delivery_pre + sdf_name.format(endDate) + this.getEND_SN(int_last);
    }

    private static String getEND_SN(Integer int_last){
        String sn = int_last + "";
        if(sn.length() == 1){
            return  "0" + sn;
        }else {
            return sn;
        }
    }

    private boolean checkBeing(String id,List<String> list){
        for(String str : list){
            if(str.equals(id)){
                return true;
            }
        }
        return false;
    }
    private boolean checkLocation(String location){
        return "默认仓库".equals(location);
    }

}
